﻿using UnityEngine;
using UnityEditor;
using System.Collections;

public class ObjectReplacer : ScriptableWizard {

	public GameObject replacement;
	public bool showDialogs = true;
	const string SHOW_DIALOG_KEY = "ObjectReplacer.showDialogs";

	//Make wizzard appear on Menu
	[MenuItem("Tools/Replace Selection", false, 1050)]
	static void CreateWizzard(){
		ScriptableWizard.DisplayWizard("Object Replacer", typeof(ObjectReplacer), "Replace and Close", "Replace");
	}

	void OnEnable(){
		showDialogs = EditorPrefs.GetBool(SHOW_DIALOG_KEY, true);
	}

	void OnWizardCreate(){
		ReplaceAll();
	}

	void ReplaceAll(){

		if(showDialogs){
			if(!EditorUtility.DisplayDialog("Are you sure?", "Do you want to replace all the selected objects with \"" + 
				replacement.name + "\" ?", "Yes", "Cancel"))
				return;
		}

		//Only topLevel that are not part of prefabs assets;
		Transform[] transforms = Selection.GetTransforms(SelectionMode.TopLevel | SelectionMode.ExcludePrefab);

		int count = 0;
		foreach(Transform t in transforms){
			if(EditorUtility.DisplayCancelableProgressBar("Replacement in progress", 
				"Replacing " + t.name, count / (float)transforms.Length))
				break;
			ReplaceObject(t);
			count++;
		}

		if(showDialogs){
			EditorUtility.DisplayDialog("Done", count + " Objects replaced", "Ok");
		}

		//Very important to clear progress bars or unity freezes
		EditorUtility.ClearProgressBar();
		ShowNotification(new GUIContent("Done"));
	}

	void ReplaceObject(Transform trans){
		GameObject newGO;
		newGO = PrefabUtility.InstantiatePrefab(replacement) as GameObject;
		newGO.transform.position = trans.position;
		newGO.transform.rotation = trans.rotation;
		newGO.transform.localScale = trans.localScale;
		newGO.transform.parent = trans.parent;

		//Allows us to be UNDOable
		Undo.RegisterCreatedObjectUndo(newGO, "Replaced Objects");
		Undo.DestroyObjectImmediate(trans.gameObject);
	}

	void OnWizardOtherButton(){
		ReplaceAll();
	}


	void OnWizardUpdate(){
		Transform[] transforms = Selection.GetTransforms(SelectionMode.TopLevel | SelectionMode.ExcludePrefab);
		helpString = transforms.Length
			+ " Objects selected for replacement";

		errorString = "";
		isValid = true;

		if(replacement == null){
			errorString += "No replacement object selected \n";
			isValid = false;
		}
		if(transforms.Length < 1){
			errorString += "No Objects selected for replacement \n";
			isValid = false;
		}

		EditorPrefs.SetBool(SHOW_DIALOG_KEY, showDialogs);


	}

	void OnSelectionChange(){
		OnWizardUpdate();
	}

}
